package com.demo.crm.springboot3security.util;

import java.util.UUID;

import org.slf4j.MDC;

/**
 * 请求链路ID工具类
 */
public class TraceIdUtil {
    private static final String TRACE_ID = "traceId";

    /**
     * 生成新的链路ID
     */
    public static String generateTraceId() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 获取当前链路ID
     */
    public static String getCurrentTraceId() {
        String traceId = MDC.get(TRACE_ID);
        if (traceId == null) {
            traceId = generateTraceId();
            MDC.put(TRACE_ID, traceId);
        }
        return traceId;
    }

    /**
     * 设置链路ID
     */
    public static void setTraceId(String traceId) {
        if (traceId != null) {
            MDC.put(TRACE_ID, traceId);
        }
    }

    /**
     * 清除链路ID
     */
    public static void clearTraceId() {
        MDC.remove(TRACE_ID);
    }
}